import java.util.List;

public class MySingleList implements IList{
    //创建链表基本属性
    static class ListNode{
        public int val;//值域
        public ListNode next;//next域
        //构造器，用于 传值
        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode head;//链表的头节点
  //创建一个链表
    public void creatList() {
        ListNode node1 = new ListNode(10);
        ListNode node2 = new ListNode(20);
        ListNode node3 = new ListNode(15);
        ListNode node4 = new ListNode(30);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        this.head = node1;
    }

    @Override
    public void addFirst(int data) {
    ListNode cur = new ListNode(data);
    cur.next = head;
    this.head = cur;
    }

    @Override
    public void addList(int data) {
    ListNode cur = head;
    ListNode node = new ListNode(data);
    if(head == null) {
        head = node;
    }
    while(cur.next != null) {
        cur = cur.next;
    }
    cur.next = node;
    }

    @Override
    public void addIndex(int index, int data) {
        ListNode node = new ListNode(data);
        if (index < 0 || index > size()) {
            throw new IndextException("index不合法...");
        }
        else if (index == 0) {
            addFirst(data);//头插
        }
        else if (index == size()) {
            addList(data);//尾插
        } else {
            //中间插入
            //首先查找index前一个位置在哪
            ListNode cur = searchPreIndex(index);
            node.next = cur.next;
            cur.next = node;
        }
    }
    public ListNode searchPreIndex(int index) {
        ListNode cur = head;
        int count = 0;
        while(count != index-1){
            cur = cur.next;
            count++;
        }
        return cur;
    }

    @Override
    public boolean contains(int key) {
        ListNode cur = head;
        while(cur != null) {
            if(cur.val == key) {
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

    @Override
    public void remove(int key) {

    }

    @Override
    public void removeAllKey(int key) {

    }

    @Override
    public int size() {
    ListNode cur = head;
    int count = 0;
    while(cur != null) {
        count++;
        cur = cur.next;
    }
    return count;
    }

    @Override
    public void clear() {
        head = null;
    }

    public void display() {
        ListNode cur = head;
        while(cur!=null) {
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
        System.out.println();
    }
}
